Overriding
When the base and derived classes has the same function name it is called overriding .
New: It is possible for a derived class to define a member that has the same name as a member in its base class. When this happens, the member in the base class is hidden within the derived class. While this is not technically an error in C#, the compiler will issue a warning message. to prevent this warning, the derived class member must be preceded by the new keyword
new is separate and distinct from its use when creating an object instance.
Program on Overriding members
using System;
class abc
{
protected int a;
public void get(int x)
{
a = x;
}
}
class xyz : abc
{
new int a; // hides the a in abc class
public void get1(int x)
{
a = x;
}
public void put()
{
Console.WriteLine("Sum of 2nos" + (a + base.a));
}
}
class sample
{
public static void Main(String[] args)
{
xyz x = new xyz();
x.get(10);
x.get1(20);
x.put();
}
}
Program on Overriding methods
using System;
class abc
{
protected int a;
public void get(int x)
{
a = x;
Console.WriteLine("Value of a" + a);
}
}
class xyz : abc
{
new int a;
public new void get(int x)
{
a = x;
base.get(2);
}
public void put()
{
Console.WriteLine("Sum of 2nos" + (a + base.a));
}
}
class sample
{
public static void Main(String[] args)
{
xyz x = new xyz();
x.get(10);
x.put();
}
}
Program on overriding members and polymorphism
using System;
class abc
{
protected int a;
public abc(int x)
{
a = x;
}
public void put()
{
Console.WriteLine("Value of a" + a);
}
}
class xyz : abc
{
int b;
public xyz(int x, int y): base(x)
{
b = y;
}
public new void put()
{
Console.WriteLine("Value of a" + a);
Console.WriteLine("value of b" + b);
}
}
class sample
{
public static void Main(String[] args)
{
abc x = new abc(5);
xyz y = new xyz(3,6);
abc z;
z = x;
z.put();
z = y;
y.put();
z.put();
}
}